import { Component, Injector, ElementRef, ViewChild } from "@angular/core";
import { Tabs, NavController } from "ionic-angular";
import { IonicPage } from "ionic-angular";
import { StorageService } from "./../../providers/StorageService";
import { UserPosVo } from "./../../model/UserPosVo";
import { BasePage } from "../basePage";
import { Events } from "ionic-angular";
import { ContactPage } from "./../contact/contact";
import { RcmdPage } from "./../rcmd/rcmd";
import { LocalNotifications } from "@ionic-native/local-notifications";

import { NailShopPage } from "./../nail-shop/nail-shop";
import { StyleService } from "./../../providers/StyleService";
import {
  VEERSION,
  PIC_URL,
  DOMAIN,
  PAGE_SIZE
} from "./../../providers//Config";
import { NativeService } from "../../providers/NativeService";


import { Geolocation } from '@ionic-native/geolocation';
// baidu map
declare var BMap;
declare var BMAP_STATUS_SUCCESS;

declare var layer;
declare let baidumap_location: any;
declare var $: any;
declare var window;
// gaode map
// declare var AMap;
@IonicPage({ name: "home" })
@Component({
  selector: "page-home",
  templateUrl: "home.html",
  providers: [StyleService, NativeService]
})
export class HomePage extends BasePage {

  locationIP: any;
  userMapInfo: any;
  cityName: any;
  @ViewChild('map') map_container: ElementRef;
  map: any;//地图对象
  marker: any;//标记
  geolocation1: any;
  myIcon: any;


  fullPush = [];
  fullPush1 = [];
  fullPush2 = [];
  fullPush3 = [];
  fullPushh = [];
  fullPush11 = [];
  fullPush22 = [];
  fullPush33 = [];
  // styleData=[];


  hands = [];
  types = [];
  tools = [];
  hands2 = [];
  types2 = [];
  tools2 = [];
  //
  data = {};
  adList = [];
  popAdObj = [];
  picUrl = PIC_URL;
  currCity = "北京";
  userPosVo = {};
  contentArea = "RcmdPage"; //NailShopPage  美店
  //剩下弹出的款式 ,从 RcmdPage 赋值过来的
  otherStyleList = [];
  func = "recommend";

  /**搜索参数 */
  searchApiVo = [];
  searchApiVo2 = {
    search_type: "",
    search_key: ""
  };

  /**
   * 分页组件对象
   */
  private pagingObj: any;
  //当前页码
  private page = 0;
  //当前list 的数组
  styleMore = [];
  //上一个点击的类目
  previousItem: any;
  /** 顶部刷新 */
  userinfo: any;
  /**
   * 当前选中的styleId
   */
  private styleId;
  ids: "";

  myEvent: any;

  isClick: boolean = false;
  isOpen: boolean = false; //侧滑框是否处于打开状态
  haveId: boolean; //没登陆隐藏悬浮


  constructor(
    injector: Injector,
    private localNotifications: LocalNotifications,
    public stc: StorageService,
    public nativeService: NativeService,
    public stgSc: StorageService,
    public events: Events,
    public styleProvider: StyleService,
    public NavCtrl: NavController,
    private geolocation: Geolocation,
    
  ) {
    super(injector);
    this.userinfo = this.stc.read("userinfo");
    // this.getLocationByIp();

    let full = this.stc.read("full");
    console.log(full);
    this.myIcon = new BMap.Icon("assets/icon/favicon.ico", new BMap.Size(30, 30));

    this.geolocation.getCurrentPosition().then(resp => {
      console.log(resp)
      // alert(resp)
      // resp.coords.latitude
      // resp.coords.longitude
    }).catch((error) => {
      // alert(error)
      console.log('Error getting location', error);
    });

    
  }


  // ionViewWillEnter(){
  //  // $(".fanren").css("display","block");
  // }


  //每次调用
  ionViewDidEnter() {
    this.getLocationByIp();
    console.log(this.cityName)
    $(".btn").removeClass("active");
    $(".btn")
      .eq(0)
      .addClass("active");
    this.getSearchConditionAPI();

    this.all();
    if (this.userinfo == null) {
      this.haveId = false;

    } else {
      this.haveId = true;
    }
    this.userMapInfo = this.stc.read("userMapInfo");
    console.log(this.userMapInfo)
    if (typeof (this.userMapInfo) == 'object') {
      console.log(6);
      if (this.userMapInfo == null || this.userMapInfo['city'] == null || this.userMapInfo == undefined) {
        // console.log(99)
        this.currCity = '北京';
      } else if (this.userMapInfo.city) {

        console.log(8);
        this.currCity = this.userMapInfo.city;
      }
    }

    console.log(this.currCity);
    console.log(this.cityName)


  }
  ionViewDidLeave() {
    console.log("离开页面的时候");
  }
  toBaidu() {
    this.navCtrl.push("BaiduMapPage")
  }
  //只调用一次 ，注意：子的 ionViewDidLoad 在它之前
  ionViewDidLoad() {

    this.getNotifi();

    // document.title = "精选"
    // let stxt = document.querySelector(".searchbar-input");
    // stxt["disabled"] = true;

    //从缓存中取上次定位的城市 ，有，直接返回 -没有就百度定位，百度定位失败，让用户手工选城市
    //this.userPosVo = this.storageService.read('userMapInfo');
    if (this.userPosVo) {
      //this.currCity = this.userPosVo['city'];
      //this.doGetAd();
    } else {
      //this.getUserCurrentPos();
    }
    //先检查是否有升级 -----> 无 再弹出广告  ---------- 因为浏览器下无法取版本号，所以直接改为  config.js 来设置当前版本号了
    // this.platform.ready().then(async () => {
    //   let needUpdate = await this.nativeService.detectionUpgrade();
    //   if (!needUpdate) {  //不需要升级
    //     this.doGetAd();
    //   }});
    this.getNotifi();

  }

  /*搜索部分的函数 当点击搜索框的时候 */
  getFocus($event) {
    /*使输入框不能得到焦点*/
    $event.target.blur();
    /*跳转到搜索页面*/
    // this.navCtrl.push("SearchPage");
    this.modalCtrl.create("SearchPage").present();

  }
  /**IP定位 */
  getLocationByIp() {
    let myCity = new BMap.LocalCity();
    // console.log(myCity);
    myCity.get(result => {
      console.log(result)
      this.locationIP = result;
      this.cityName = result.name;
      // this.map.setCenter(this.cityName);
      // alert("当前定位城市:" + this.cityName);
    });
    // alert("当前定位城市:" + this.cityName);
    if (this.currCity != this.cityName && this.cityName != null) {
      this.alertCtrl.create({
        title: '定位提醒',
        message: '是否定位到当前城市？',
        buttons: [
          {
            text: '取消',
            handler: () => {
              // this.currCity = this.userMapInfo.city;
            }
          },
          {
            text: '确定',
            handler: () => {
              this.currCity = this.cityName;
              this.stgSc.write("userMapInfo", {})
              this.userPosVo = {};
              this.userPosVo["latitude"] = this.locationIP.latitude; //纬度
              this.userPosVo["longitude"] = this.locationIP.longitude;
              this.userPosVo["city"] = this.currCity = this.cityName;
              // this.currCity = this.userPosVo["city"];
              this.stgSc.write("userMapInfo", this.userPosVo);
            }
          }
        ]
      }).present();
    }
  }

  /**
   * 去取广告数据
   */
  async doGetAd() {
    //取广告
    this.styleProvider.getAdlist({ pos_id: 3 }).then(res => {
      if (res) {
        this.navCtrl["_children"][0]._views[0].instance.adList = res.data; //轮播广告
        //  this.popAdObj = res.data[2][0]; //弹出广告页
      }
    });

    //再读取本地版本与服务器版本
    // var res = await this.http.get(DOMAIN + "update.json?rnd=" + new Date().getTime()).toPromise()
    // var verObj = JSON.parse(res['_body']);
    // if (parseFloat(verObj['version']) > parseFloat(VEERSION)) {
    //   this.nativeService.promatUpdate(verObj['desc']);
    // } else {
    //   this.showPopAd()
    // }
  }

  getNotifi() {
    console.log("infoGetnotifi");
    this.localNotifications.schedule({
      id: 1,
      title: "美甲艺境",
      text: "精选款式又有新品看，快去看看哪款适合你",
      sound: null,
      data: {
        type: 0, //0---- 打开网址
        url: ""
      }
    });
  }

  // 打开右侧菜单
  openMenu() {
    this.menuCtrl.open();
  }

  //选择了首页某个大模块
  selectFunc(funcName) {
    this.contentArea = funcName; //NailShopPage  美店
  }

  //得到用户当前坐标
  getUserCurrentPos = () => {
    this.platform.ready().then(readySource => {
      try {
        baidumap_location.getCurrentPosition(
          result => {
            // alert(JSON.stringify(result))
            if (!result.hasOwnProperty("city")) {
              //无网络无法定位,但百度还是根据浏览器返回了值
              alert("没citi" + JSON.stringify(result));
              this.openCitiChoose();
              return;
            }

            this.userPosVo = result;
            this.currCity = this.userPosVo["city"];
            // alert('result' + JSON.stringify(result));
            //  alert('getUserCurrentPos' + JSON.stringify(this.userPosVo));
            this.stgSc.write("userMapInfo", this.userPosVo);
            //   alert("写入成功"+JSON.stringify(this.userPosVo))
          },
          error => {
            // alert('百度定位信息读取失败');
            this.openCitiChoose();
            console.log("百度定位信息读取失败");
          }
        );
      } catch (error) {
        // alert('百度定位组件初始化失败' + error);
        this.openCitiChoose();

        console.log("百度定位组件初始化失败");
      }
    });
  };

  /** 打开城市选择页面 */
  openCitiChoose = () => {
    // this.navCtrl.push("CitySelectPage", {
    //   callback: this.getCitiChooseResult
    // });
    this.modalCtrl.create("CitySelectPage", {
        callback: this.getCitiChooseResult
      }).present();
  };

  //得到城市选择的结果
  getCitiChooseResult = data => {
    return new Promise((resolve, reject) => {
      this.userPosVo = {};
      this.userPosVo["latitude"] = data.latitude; //纬度
      this.userPosVo["longitude"] = data.longitude;
      this.userPosVo["city"] = data.name;
      this.currCity = this.userPosVo["city"];
      console.log(this.userPosVo);
      this.stgSc.write("userMapInfo", this.userPosVo);
      // this.cityName = this.currCity;
      // this.doGetAd();
      resolve();
    });
    // 被调用者 this.callback(city).then(()=>{ this.navCtrl.pop() });
  };
  //身份切换
  // changeTabs($event) {
  //   this.events.publish("tab:change", 1)
  // }

  //选中了某个款式
  showMoreStyle(item) {
    this.navCtrl["_children"][0]._views[0].instance.showMoreStyle(item);
    // this.previousItem.innerText = item.type_name;
  }

  //显示大图广告
  showPopAd = () => {
    let modal = this.modalCtrl.create("AdPage");
    modal.present();
  };
  /**
   * 首页里
   */
  /** 风格选择 */
  style(id) {
    console.log(id);
    this.fullPush1.push(id);
    console.log(this.fullPush1);
    if (this.fullPush1.length > 1) {
      let toast = this.toastCtrl
        .create({
          message: "每种款式只能选择一个，最多可选三种款式",
          duration: 3000
          // position:top,
        })
        .present();

      return;
    } else {
      $(".btns")
        .eq(id)
        .addClass("active1");
      $(".rem1")
        .eq(id)
        .show();
      for (var i = 0; i < this.types.length; i++) {
        if (id == i) {
          console.log(this.types[i]);
          this.fullPush.push(this.types[i]);
          console.log(this.fullPush);
        }
      }
    }
  }

  style1(id) {
    console.log(id);

    this.fullPush2.push(id);
    if (this.fullPush2.length > 1) {
      let toast = this.toastCtrl
        .create({
          message: "每种款式只能选择一个，最多可选三种款式",
          duration: 3000
          // position:top,
        })
        .present();

      return;
    } else {
      $(".btns1")
        .eq(id)
        .addClass("active2");
      $(".rem2")
        .eq(id)
        .show();
      for (var i = 0; i < this.hands.length; i++) {
        if (id == i) {
          console.log(this.hands[i]);
          this.fullPush.push(this.hands[i]);
          console.log(this.fullPush);
        }
      }
    }
  }
  style2(id) {
    console.log(id);
    this.fullPush3.push(id);
    if (this.fullPush3.length > 1) {
      let toast = this.toastCtrl
        .create({
          message: "每种款式只能选择一个，最多可选三种款式",
          duration: 3000
          // position:top,
        })
        .present();

      return;
    } else {
      $(".btns2")
        .eq(id)
        .addClass("active3");
      $(".rem3")
        .eq(id)
        .show();
      for (var i = 0; i < this.tools.length; i++) {
        if (id == i) {
          console.log(this.tools[i]);
          this.fullPush.push(this.tools[i]);
          console.log(this.fullPush);
        }
      }
    }
  }
  /** 取消选择 */
  rem1(id) {
    console.log(id);
    $(".rem1")
      .eq(id)
      .hide();
    $(".btns")
      .eq(id)
      .removeClass("active1");
    for (let ids of this.fullPush1) {
      if (ids == id) {
        this.fullPush1 = [];
      }
    }
    for (var i = 0; i < this.types.length; i++) {
      if (id == i) {
        console.log(this.types[i]);
        this.fullPush.indexOf(this.types[i]);
        console.log(this.fullPush.indexOf(this.types[i]));
        this.fullPush.splice(this.fullPush.indexOf(this.types[i]), 1);
        console.log(this.fullPush);
      }
    }
    event.stopPropagation();
  }
  rem2(id) {
    console.log(id);
    $(".rem2")
      .eq(id)
      .hide();
    $(".btns1")
      .eq(id)
      .removeClass("active2");
    for (let ids of this.fullPush2) {
      if (ids == id) {
        this.fullPush2 = [];
      }
    }
    for (var i = 0; i < this.hands.length; i++) {
      if (id == i) {
        console.log(this.hands[i]);
        this.fullPush.indexOf(this.hands[i]);
        console.log(this.fullPush.indexOf(this.hands[i]));
        this.fullPush.splice(this.fullPush.indexOf(this.hands[i]), 1);
        console.log(this.fullPush);
      }
    }
    event.stopPropagation();
  }
  rem3(id) {
    console.log(id);
    $(".rem3")
      .eq(id)
      .hide();
    $(".btns2")
      .eq(id)
      .removeClass("active3");
    for (let ids of this.fullPush3) {
      if (ids == id) {
        this.fullPush3 = [];
      }
    }
    for (var i = 0; i < this.tools.length; i++) {
      if (id == i) {
        console.log(this.tools[i]);
        this.fullPush.indexOf(this.tools[i]);
        console.log(this.fullPush.indexOf(this.tools[i]));
        this.fullPush.splice(this.fullPush.indexOf(this.tools[i]), 1);
        console.log(this.fullPush);
      }
    }
    event.stopPropagation();
  }
  /** 首页里的重置 */
  all() {
    $(".btns").removeClass("active1");
    $(".btns1").removeClass("active2");
    $(".btns2").removeClass("active3");
    $(".rem1").hide();
    $(".rem2").hide();
    $(".rem3").hide();
    this.fullPush1 = [];
    this.fullPush2 = [];
    this.fullPush3 = [];
    this.fullPush = [];
  }

  /**点击确定 完成搜索 */
  async getStyleByid(user) {
    let full = [];
    for (let key of this.fullPush) {
      // full.push(key.id);
      // let keysId = full.toString();
      this.searchApiVo.push(key.id);
    }
    console.log(this.searchApiVo);
    let res = await this.styleProvider.getStyleByid(this.searchApiVo);
    console.log(res);
    if (res.error_code == 0) {
      let toast = this.toastCtrl
        .create({
          message: "数据获取成功",
          duration: 1500
        })
        .present();
    }
    //this.doRefresh(this.pagingObj);
    this.menuCtrl.close();
    //this.navCtrl.push("RcmdPage",{res:res})
    //通过事件订阅，让rcmd接收到搜索参数并启用方法
    this.events.publish("user:created", this.searchApiVo, Date.now());
    console.log(this.searchApiVo);
  }

  /**
   * 美图描述里的风格选择
   */
  stylee(id) {
    if (this.fullPushh.length < 4) {
      for (let i = 0; i < this.types2.length; i++) {
        if (id == i) {
          for (let j = 0; j < this.fullPushh.length; j++) {
            if (this.types2[i] == this.fullPushh[j]) {
              this.remm1(id);
            }
          }
          $(".btnsd")
            .eq(id)
            .addClass("active1");
          $(".rem1d")
            .eq(id)
            .show();
          this.fullPushh.push(this.types2[i]);
          console.log(this.fullPushh);
        }
      }
    } else {
      let toast = this.toastCtrl
        .create({
          message: "多可选四种款式",
          duration: 3000
        })
        .present();
    }
  }
  stylee1(id) {
    if (this.fullPushh.length < 4) {
      for (let i = 0; i < this.hands2.length; i++) {
        if (id == i) {
          for (let j = 0; j < this.fullPushh.length; j++) {
            if (this.hands2[i] == this.fullPushh[j]) {
              this.remm2(id);
            }
          }
          $(".btns1d")
            .eq(id)
            .addClass("active2");
          $(".rem2d")
            .eq(id)
            .show();
          this.fullPushh.push(this.hands2[i]);
          console.log(this.fullPushh);
        }
      }
    } else {
      let toast = this.toastCtrl
        .create({
          message: "多可选四种款式",
          duration: 3000
          // position:top,
        })
        .present();
    }
  }

  //描述里取消选择
  remm1(id) {
    console.log(id);
    $(".rem1d")
      .eq(id)
      .hide();
    $(".btnsd")
      .eq(id)
      .removeClass("active1");
    for (let ids of this.fullPush11) {
      if (ids == id) {
        this.fullPush11 = [];
      }
    }
    for (var j = 0; j < this.types2.length; j++) {
      if (id == j) {
        console.log(this.types2[j]);
        this.fullPushh.indexOf(this.types2[j]);
        console.log(this.fullPushh.indexOf(this.types2[j]));
        this.fullPushh.splice(this.fullPushh.indexOf(this.types2[j]), 1);
        console.log(this.fullPushh);
      }
    }
    event.stopPropagation();
  }
  remm2(id) {
    console.log(id);
    $(".rem2d")
      .eq(id)
      .hide();
    $(".btns1d")
      .eq(id)
      .removeClass("active2");
    for (let ids of this.fullPush22) {
      if (ids == id) {
        this.fullPush22 = [];
      }
    }
    for (var i = 0; i < this.hands2.length; i++) {
      if (id == i) {
        console.log(this.hands2[i]);
        this.fullPushh.indexOf(this.hands2[i]);
        console.log(this.fullPushh.indexOf(this.hands2[i]));
        this.fullPushh.splice(this.fullPushh.indexOf(this.hands2[i]), 1);
        console.log(this.fullPushh);
      }
    }
    event.stopPropagation();
  }
  //描述里重置
  /** 重置 */
  allbac() {
    $(".btnsd").removeClass("active1");
    $(".btns1d").removeClass("active2");
    $(".btns2d").removeClass("active3");
    $(".rem1d").hide();
    $(".rem2d").hide();
    $(".rem3d").hide();
    this.fullPush11 = [];
    this.fullPush22 = [];
    this.fullPush33 = [];
    this.fullPushh = [];
    console.log(this.fullPushh);
  }
  async ok() {
    let full = [];
    let full2 = [];
    this.stc.write("full", this.fullPushh); //带id和款式名字
    if (this.fullPushh.length > 4) {
      this.showAlert("最多只能选择4个标签哦！");
      console.log(this.fullPushh);
    } else {
      for (let key of this.fullPushh) {
        full.push(key.id);
        full2.push(key.type_name);
        console.log(this.fullPushh);
        let keysId = full.toString();
        let keysName = full2.toString();
        this.searchApiVo2.search_type = keysId;
        this.searchApiVo2.search_key = keysName;
      }
      console.log(full);
      this.stc.write("full2", full2); //美图描述里的带名字
      this.stc.write("full", full); //美图描述里只有id
      let res = await this.styleProvider.searchAPI(this.searchApiVo);
      console.log(res);
      if (res.error_code == 0) {
        let toast = this.toastCtrl
          .create({
            message: "数据获取成功",
            duration: 1500
          })
          .present();
      }
      this.menuCtrl.close();
    }
  }

  async doRefresh(refresher) {
    console.log(refresher);
    this.pagingObj = refresher;
    this.page = 0;
    this.styleMore = [];
    let param = {
      //未读页码
      user_id: this.userinfo.user_id,
      page_size: PAGE_SIZE,
      page_pos: 0,
      nail_type: this.styleId,
      page_buy: 0
      // bar_type: this.ids
    };
    if (this["page1_" + this.styleId]) {
      this.styleMore = this["page1_" + this.styleId];
      // this.pagingObj.complete();
      return;
    }
    console.log(param);
    // this.pagingObj.complete();
    let res = await this.styleProvider.getStyleByid(param);
    console.log(res);
    this.styleMore = this.styleMore.concat(res.data);
    console.log(this.styleMore);
    console.log(this.ids);
  }
  /** 获取款式风格 */

  async getSearchConditionAPI() {
    console.log(this.data); //无数据
    let res = await this.styleProvider.getSearchConditionAPI(this.data);
    // console.log(res);
    console.log(res);
    if (!res) {
      res = {
        hands: [],
        hands2: [],
        type: [],
        tools: [],
        tools2: []
      };
    }
    this.hands = res.hands;
    this.hands2 = res.hands;
    this.types = res.type;
    this.types2 = res.type;
    this.tools = res.tools;
    this.tools2 = res.tools;
    console.log(this.hands);
    console.log(this.types);
    console.log(this.tools);
  }

  /** 跳转更多 */
  add1() {
    // console.log(1)
    // $(".fanren").css("display","none");
    // this.navCtrl.push("AddPage");
    // setTimeout(() => {
    //
    // }, 500);

    let modal = this.modalCtrl.create("AddPage");
    modal.present();
  }

  /**极光推送 */
}
